package com.zs.spring.web.servlet.controller

import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.context.request.async.DeferredResult
import java.util.concurrent.ArrayBlockingQueue
import kotlin.random.Random

/**
 *
 * @description
 * @author madison
 * @date 2021/6/3 15:02
 *
 */
@RestController
@EnableScheduling
class HelloWorldAsyncController {
    val queue = ArrayBlockingQueue<DeferredResult<String>>(5)
    val random = Random

    @Scheduled(fixedRate = 5000)
    fun process() {
        var result: DeferredResult<String>?
        do {
            result = queue.take()
            // 随机超时时间
            var timeout = random.nextLong(100)
            Thread.sleep(timeout)
            result.setResult("Hello,World")
            println("执行计算结果，消耗：$timeout ms.")
        } while (result != null)
    }
}